package com.buaa.daas.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buaa.daas.constant.LocatChangeType;
import com.buaa.daas.constant.NotAtSchoolType;
import com.buaa.daas.constant.StuDailyClockType;
import com.buaa.daas.entity.StuDailyClockMessage;
import com.buaa.daas.entity.StuInfo;
import com.buaa.daas.mapper.StuDailyClockMessageMapper;
import com.buaa.daas.service.StuDailyClockMessageService;
import com.buaa.daas.service.StuInfoService;
import com.buaa.daas.vo.StuDailyClockMessageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author WangKangMing
 * @since 2021-06-04
 */
@Controller
public class StuPresetController {

    @Autowired
    private StuInfoService stuInfoService;

    @Autowired
    private StuDailyClockMessageService stuDailyClockMessageService;

    @Autowired
    private StuDailyClockMessageMapper stuDailyClockMessageMapper;

    @GetMapping("/preset/delete/{autoid}")
    String deletePreset(@PathVariable("autoid") String autoid ,HttpServletRequest request, Model model){
        /**
         * 删除自带权限校验
         */
        StuInfo stuInfo = stuInfoService.getInfoByRequest(request);
        int delete = stuDailyClockMessageService.deleteByIdAndStuNum(autoid, stuInfo);
        if(delete == 1) {
            model.addAttribute("deleteMsg","删除成功");
        }else{
            model.addAttribute("deleteMsg","删除失败，请不要恶意删除别人的预约或重复删除。");
        }

        return "preset";
    }

    @GetMapping("/preset")
    String getPreset(HttpServletRequest request, Model model){

        StuInfo infoByRequest = stuInfoService.getInfoByRequest(request);
        String stuNum = infoByRequest.getStuNum();
        //先判断有没有完善信息，特别是eaisess值
        QueryWrapper<StuInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_num",stuNum);
        StuInfo selectOne = stuInfoService.getBaseMapper().selectOne(wrapper);
        if(selectOne.getStuEaisess() == null || "".equals(selectOne.getStuEaisess())){
            model.addAttribute("eaisessMsg","只有登记Token值之后才能使用打卡预约服务");

            HashMap<String, String> map = new HashMap<>();
            map.put("stuNum",stuNum!=null?stuNum:"");
            map.put("stuName",infoByRequest.getStuName()!=null?infoByRequest.getStuName():"");
            map.put("stuEmail",infoByRequest.getStuEmail()!=null?infoByRequest.getStuEmail():"");
            map.put("stuEaisess",infoByRequest.getStuEaisess()!=null?infoByRequest.getStuEaisess():"");

            model.addAllAttributes(map);
            return "stuinfo";
        }

        //
        List<StuDailyClockMessage> stuDailyClockMessageList = stuDailyClockMessageService.getStuDailyClockMessageList(stuNum);

        List<StuDailyClockMessageVo> stuDailyClockMessageVos = stuDailyClockMessageList.stream().map((so) -> {
            StuDailyClockMessageVo vo = new StuDailyClockMessageVo();
            vo.setStuNum(so.getStuNum());
            vo.setAutoId(so.getAutoId());
            vo.setLocation(so.getLocation());
            vo.setAtSchoolOrNot(so.getAtSchoolOrNot());
            vo.setNotAtSchoolOtherTypeDescription(so.getNotAtSchoolOtherTypeDescription());

            //不能switch case，暂时使用这么low的方式
            Integer notAtSchoolTypeObj = so.getNotAtSchoolType();
            if(notAtSchoolTypeObj == null){
                vo.setNotAtSchoolType(null);
            }else{
                int notAtSchoolType = notAtSchoolTypeObj;
                if (notAtSchoolType == NotAtSchoolType.NotAtSchoolTypeEnum.LEAVING_TEMPORARILY.getCode()) {
                    vo.setNotAtSchoolType(NotAtSchoolType.NotAtSchoolTypeEnum.LEAVING_TEMPORARILY.getMsg());
                } else if (notAtSchoolType == NotAtSchoolType.NotAtSchoolTypeEnum.RETURNING_HOME.getCode()) {
                    vo.setNotAtSchoolType(NotAtSchoolType.NotAtSchoolTypeEnum.RETURNING_HOME.getMsg());
                } else if (notAtSchoolType == NotAtSchoolType.NotAtSchoolTypeEnum.STUDYING_ABROAD.getCode()) {
                    vo.setNotAtSchoolType(NotAtSchoolType.NotAtSchoolTypeEnum.STUDYING_ABROAD.getMsg());
                } else if (notAtSchoolType == NotAtSchoolType.NotAtSchoolTypeEnum.TRAVELLING_INTERNSHIP.getCode()) {
                    vo.setNotAtSchoolType(NotAtSchoolType.NotAtSchoolTypeEnum.TRAVELLING_INTERNSHIP.getMsg());
                } else if (notAtSchoolType == NotAtSchoolType.NotAtSchoolTypeEnum.ILLNESS_SUSPENSION.getCode()) {
                    vo.setNotAtSchoolType(NotAtSchoolType.NotAtSchoolTypeEnum.ILLNESS_SUSPENSION.getMsg());
                } else if (notAtSchoolType == NotAtSchoolType.NotAtSchoolTypeEnum.OTHERS.getCode()) {
                    vo.setNotAtSchoolType(NotAtSchoolType.NotAtSchoolTypeEnum.OTHERS.getMsg());
                }
            }

            Integer locatChangeTypeObj = so.getLocatChangeType();
            if(locatChangeTypeObj == null){
                vo.setLocatChangeType(null);
            }else{
                int locatChangeType = locatChangeTypeObj;
                if (locatChangeType == LocatChangeType.LocatChangeTypeEnum.VISITING_RELATIVES.getCode()) {
                    vo.setLocatChangeType(LocatChangeType.LocatChangeTypeEnum.VISITING_RELATIVES.getMsg());
                } else if (locatChangeType == LocatChangeType.LocatChangeTypeEnum.TRAVELING.getCode()) {
                    vo.setLocatChangeType(LocatChangeType.LocatChangeTypeEnum.TRAVELING.getMsg());
                } else if (locatChangeType == LocatChangeType.LocatChangeTypeEnum.HOMECOMING.getCode()) {
                    vo.setLocatChangeType(LocatChangeType.LocatChangeTypeEnum.HOMECOMING.getMsg());
                } else if (locatChangeType == LocatChangeType.LocatChangeTypeEnum.OTHERS.getCode()) {
                    vo.setLocatChangeType(LocatChangeType.LocatChangeTypeEnum.OTHERS.getMsg());
                }
            }


            vo.setStuName(stuNum);
            QueryWrapper<StuInfo> stuInfoQueryWrapper = new QueryWrapper<>();
            stuInfoQueryWrapper.eq("stu_num",stuNum);
            StuInfo stuInfo = stuInfoService.getBaseMapper().selectOne(stuInfoQueryWrapper);
            vo.setStuName(stuInfo.getStuName());

            vo.setStartTime(so.getStartTime());
            vo.setEndTime(so.getEndTime());
            vo.setAutoId(so.getAutoId());
            return vo;
        }).sorted(Comparator.comparing(StuDailyClockMessageVo::getStartTime)).collect(Collectors.toList());

        model.addAttribute("stuDailyClockMessageList",stuDailyClockMessageVos);

        return "preset";
    }

    @PostMapping("/preset")
    String postPreset(HttpServletRequest request,
                      @RequestParam("startTime") String  startTime,
                      @RequestParam("endTime") String  endTime,
                      @RequestParam("atSchoolOrNot") String  atSchoolOrNot,
                      @RequestParam("notAtSchoolType") String  notAtSchoolType,
                      @RequestParam("notAtSchoolOtherTypeDescription") String  notAtSchoolOtherTypeDescription,
                      @RequestParam("dailyClockLongitude") String  dailyClockLongitude,
                      @RequestParam("dailyClockLatitude") String  dailyClockLatitude,
                      @RequestParam("location") String location,
                      @RequestParam("locationSimple") String locationSimple,
                      @RequestParam("locatChangeType") String  locatChangeType,
                      @RequestParam("locatChangeOtherTypeDescription") String  locatChangeOtherTypeDescription,
                      Model model){
        StuInfo infoByRequest = stuInfoService.getInfoByRequest(request);
        String stuNum = infoByRequest.getStuNum();

        StuDailyClockMessage stuDailyClockMessage = new StuDailyClockMessage();
        stuDailyClockMessage.setStuNum(stuNum);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            stuDailyClockMessage.setStartTime(dateFormat.parse(startTime));
            stuDailyClockMessage.setEndTime(dateFormat.parse(endTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        int compare = stuDailyClockMessage.getStartTime().compareTo(stuDailyClockMessage.getEndTime());
        // 如果startTime早于endTime，那么结果是-1
        // 如果startTime等于endTime，那么结果是0
        // 如果startTime晚于endTime，那么结果是1
        if(compare > 0){
            //可以是同一天，可以相等，但是不能大于0，那样时间不正常，这个时候应当报错
            model.addAttribute("stuDailyClockMSG", StuDailyClockType.StuDailyClockTypeEnum.STARTTIME_LATER_THAN_ENDTIME.getMsg());
            return "preset";
        }

        //时间也不能交叉
        QueryWrapper<StuDailyClockMessage> stuInfoQueryWrapper = new QueryWrapper<>();
        stuInfoQueryWrapper.eq("stu_num",stuNum);
        List<StuDailyClockMessage> stuDailyClockMessageList = stuDailyClockMessageMapper.selectList(stuInfoQueryWrapper);

        boolean flag = false;//此flag用于标记是否有重叠的时间段，默认不包含
        for (StuDailyClockMessage dailyClockMessage : stuDailyClockMessageList) {
            Date startTimeQuery = dailyClockMessage.getStartTime();
            Date endTimeQuery = dailyClockMessage.getEndTime();
            //
            if(!(stuDailyClockMessage.getStartTime().compareTo(endTimeQuery) > 0 || stuDailyClockMessage.getEndTime().compareTo(startTimeQuery)<0)){
                //存在重叠
                flag = true;
                model.addAttribute("stuDailyClockMSG",StuDailyClockType.StuDailyClockTypeEnum.TIME_OVERLAP.getMsg());
                break;
            }
        }

        if(flag){
            //说明所预约的时间段与现有的有交叉
            return "preset";
        }


        int atSchoolOrNotInt = Integer.parseInt(atSchoolOrNot);
        stuDailyClockMessage.setAtSchoolOrNot(atSchoolOrNotInt);

        if(atSchoolOrNotInt == 1){
            //1表示在校
            stuDailyClockMessage.setNotAtSchoolType(null);
        }else{
            //0表示不在校
            int notAtSchoolTypeInt = Integer.parseInt(notAtSchoolType);
            stuDailyClockMessage.setNotAtSchoolType(notAtSchoolTypeInt);
            if(NotAtSchoolType.NotAtSchoolTypeEnum.OTHERS.getCode() == notAtSchoolTypeInt){
                stuDailyClockMessage.setNotAtSchoolOtherTypeDescription(notAtSchoolOtherTypeDescription);
            }else{
                stuDailyClockMessage.setNotAtSchoolOtherTypeDescription("");
            }
        }

        int locatChangeTypeInt = Integer.parseInt(locatChangeType);
        if(locatChangeTypeInt == LocatChangeType.LocatChangeTypeEnum.OTHERS.getCode()){
            stuDailyClockMessage.setLocatChangeOtherTypeDescription(locatChangeOtherTypeDescription);
        }else{
            stuDailyClockMessage.setLocatChangeOtherTypeDescription("");
        }

        //设置经纬度和简略位置信息：
        BigDecimal dailyClockLongitudeBigDecimal = new BigDecimal(dailyClockLongitude);
        BigDecimal dailyClockLatitudeBigDecimal = new BigDecimal(dailyClockLatitude);
        stuDailyClockMessage.setDailyClockLongitude(dailyClockLongitudeBigDecimal);
        stuDailyClockMessage.setDailyClockLatitude(dailyClockLatitudeBigDecimal);
        stuDailyClockMessage.setLocation(location);
        stuDailyClockMessage.setLocationSimple(locationSimple);

        int save = stuDailyClockMessageService.saveStuDailyClockMessage(stuDailyClockMessage);

        return "redirect:/preset";
    }
}

